#include <cv.h> 
#include <highgui.h> 
#include <stdio.h>
#include <string.h>


		//global variable declarations
int catchCoordinates = 0;


		//class definitions
class coordinates
{
  public:
	  int x;
	  int y;
}mouseUp, mouseDown;


		//function declarations
void mouseHandler(int, int, int, int, void *);
void trackMouseCoordinates(int, int);


		//function definitions

// keep track of mouse actions
void mouseHandler(int event, int x, int y, int flags, void* param)
{
  switch(event)
  {
    case CV_EVENT_LBUTTONDOWN:
        printf("Left button down -> x %d -> y %d\n",x,y);
        catchCoordinates = 1;
	trackMouseCoordinates(x, y);
        break;

    case CV_EVENT_LBUTTONUP:
        printf("Left button up -> x %d -> y %d\n",x,y);
	if(catchCoordinates == 1)
	{
	  catchCoordinates = 0;
          trackMouseCoordinates(x, y);
	}
	break;
  }
  

}

//store mouseCoordinates into the class
void trackMouseCoordinates(int x, int y)
{
  if(catchCoordinates == 1)
  {
    mouseDown.x = x;
    mouseDown.y = y;
  }
  if(catchCoordinates == 0)
  {
    mouseUp.x = x;
    mouseUp.y = y;
  }
}
		//main function
int main()
{
  //local declarations
  IplImage* frame = 0; 
  CvCapture* capture = 0;
  int key = 0;

  printf("Hello %d\n", catchCoordinates);
  
  capture = cvCaptureFromCAM( CV_CAP_ANY );
   
  if(!capture) 
  {
    fprintf( stderr,"Cannot initialize webcam\n");
    return 1; 
  }
  cvNamedWindow("Display", CV_WINDOW_AUTOSIZE); 
  
  while (key != 'q')
  {
    frame = cvQueryFrame( capture );
    if(!frame)
      printf("Null frame\n");
    cvShowImage("Display", frame); 
    key = cvWaitKey(2);
    cvSetMouseCallback("Display", mouseHandler, 0);
  }
  
  //cvSaveImage("imgName.jpeg" ,capture);
  cvDestroyWindow("Display");
  cvReleaseCapture( &capture );
  return 0;
}
